// pages/signIn/signIn.js
const app = getApp()
const util = require('../../../../../utils/util.js')
const lbbService = require('../../../../service/service.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    pageSize: 50,
    nameSearch:true,
    desc:'',
    top:'395',//380 340
    scrollHeight:'350',//480 300
    selectorArray: [0,0,0],
    selectedHosList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      onDuty:parseInt(options.onDuty),
      date:util.getNowDate(),
      scrollHeight:app.getScrollHeight(245)
    })
    if(this.data.onDuty==3){
      wx.setNavigationBarTitle({
        title: '出差补卡',
      })
      this.setData({
        top:'205',
        scrollHeight:app.getScrollHeight(150),
        date: options.date
      })
    }
    this.getSignTypes();
    this.getTodaySignHos();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this
    that.personalModal = that.selectComponent("#personalModal")
    that.toast = that.selectComponent("#toast")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
  /**
   * 获取cardDate师傅已经打卡的医院
   */
  getTodaySignHos(){
    let that = this;
    lbbService.getTodaySignHos({
      punchDate:that.data.date
    },res=>{
      that.setData({
        signHos:res.data
      })
    })
  },
  
  /**
   * 删除打卡的某一个医院
   */
  removeSignHos: function(e){
    util.print('removeSignHos',e);
    let id = e.currentTarget.dataset.id;
    let lbmId = e.currentTarget.dataset.lbmId;
    let lbmName = e.currentTarget.dataset.lbmName;
    let that = this;
    
    that.personalModal.showModal('确定删除'+ lbmName +'吗', function(){
      lbbService.removeSignHos({
        punchCardId:id,
        lbmId:lbmId,
      },res => {
        that.getTodaySignHos();
      })
    });
  },
  /**
   * 选择医院
   */
  hosChange(e){
    console.log('hosChange',e);
    let that = this;
    let indexArr = e.detail.value;
    let hospitalList = that.data.hospitalList;
    hospitalList.forEach(item=>{
      item.checked=false;
    })
    indexArr.forEach(index=>{
      hospitalList[index].checked = true;
    })
    that.setData({
      hospitalList:hospitalList,
    })
  },
  /**
   * 输入备注信息
   */
  inputSelectedDesc: function(e) {
    console.log('inputSelectedDesc',e);
    let that = this;
    let memo = e.detail.value;
    let hosIndex = e.currentTarget.dataset.index;
    let selectedHosList = that.data.selectedHosList;

    selectedHosList[hosIndex].memo = memo;

    that.setData({
      selectedHosList:selectedHosList,
    })
  },
  /**
   * 备注框聚焦
   */
  textareaFocus: function(){
    this.setData({
      focus:true
    })
  },
  /**
   * 输入备注信息
   */
  inputDesc: function(e) {
    console.log('inputDesc',e);
    let that = this;
    that.setData({
      focus:false
    })
    let memo = e.detail.value;
    let hosIndex = e.currentTarget.dataset.index;
    let hospitalList = that.data.hospitalList;

    hospitalList[hosIndex].memo = memo;

    that.setData({
      hospitalList:hospitalList,
    })
  },
  /**
   * 选择出差类型
   */
  selectedTypeChange: function(e) {
    let that = this
    let typeArr = e.detail.value;
    let hosIndex = e.currentTarget.dataset.index;
    let selectedHosList=that.data.selectedHosList;
    selectedHosList[hosIndex].types.forEach(item=>{
      item.checked=false;
    })
    
    let flg = false;
    typeArr.forEach(index=>{
      selectedHosList[hosIndex].types[index].checked=true;
      if(selectedHosList[hosIndex].types[index].name=='其他问题'){
        flg = true;
      }
    })
    selectedHosList[hosIndex].textareaShow = flg;
    that.setData({
      selectedHosList:selectedHosList,
    })
    that.setHospitalList();
  },
  /**
   * 选择出差类型
   */
  typeChange: function(e) {
    let that = this
    let typeArr = e.detail.value;
    let hosIndex = e.currentTarget.dataset.index;
    let hospitalList=that.data.hospitalList;
    hospitalList[hosIndex].types.forEach(item=>{
      item.checked=false;
    })
    
    let flg = false;
    typeArr.forEach(index=>{
      hospitalList[hosIndex].types[index].checked=true;
      if(hospitalList[hosIndex].types[index].name=='其他问题'){
        flg = true;
      }
    })
    hospitalList[hosIndex].textareaShow = flg;
    that.setData({
      hospitalList:hospitalList,
    })
  },


  getNowDate: function() {
    let reg = /\//g
    let nowTime = new Date()
    let nowDate = util.formatTime(nowTime).substr(0, 10).replace(reg, '-')
    return nowDate
  },

  showToast: function(text) {
    this.toast.showToast(text, '', 1500);
  },
  
  //打卡
  signIn: function () {
    let that = this;
    that.setHospitalList();
    let hospitalList = that.data.hospitalList.filter(item=>item.checked);
    let selectedHosList = that.data.selectedHosList;
    if(hospitalList.length==0&&selectedHosList.length==0){
      wx.showToast({
        title: '请选择医院',
        duration: 2500,
        icon:'none'
      })
      return;
    }
    if(hospitalList.length>0){
      let flag = false;
      hospitalList.forEach(item=>{
        let flg = true;
        item.types.forEach(item1=>{
          if(item1.checked){
            flg = false;
          }
        })
        if(flg){
          flag = true;
        }
      })
      if(flag){
        wx.showToast({
          title: '请选择原因',
          duration: 2500,
          icon:'none'
        })
        return;
      }
    }
    if(selectedHosList.length>0){
      let flag = false;
      selectedHosList.forEach(item=>{
        let flg = true;
        item.types.forEach(item1=>{
          if(item1.checked){
            flg = false;
          }
        })
        if(flg){
          flag = true;
          item.show = true;
        }
      })
      if(flag){
        that.setData({
          selectedHosList:selectedHosList
        })
        wx.showToast({
          title: '请选择原因',
          duration: 2500,
          icon:'none'
        })
        return;
      }
    }
    
    that.setMyCar();
    selectedHosList = that.data.selectedHosList;
    let punchCardInfo = new Array();
    selectedHosList.forEach(item=>{
      let types = new Array();
      item.types.forEach(item1=>{
        if(item1.checked){
          types.push(item1.name);
        }
      })
      punchCardInfo.push({lbmId:item.id,reason:types,memo:item.memo});
    })
    if(that.data.onDuty==3){
      lbbService.reSignTypes({
        cardDate:that.data.date,
        locationAddress: that.data.address ? that.data.address:'无',
        onDuty: that.data.onDuty,
        punchCardInfo:JSON.stringify(punchCardInfo)
      }, function (res) {
        that.toast.showToast('已申请补卡','success');
        setTimeout(()=>{
          wx.navigateBack({
            delta: 1
          })
        },2000)
      })
    }else {
      lbbService.signTypes({
        locationAddress: that.data.address ? that.data.address:'无',
        onDuty: that.data.onDuty,
        punchCardInfo:JSON.stringify(punchCardInfo)
      }, function (res) {
        that.toast.showToast('打卡成功','success');
        setTimeout(()=>{
          wx.navigateBack({
            delta: 1
          })
        },2000)
      })
    }
  },
  getSignTypes:function(){
    let that = this;
    lbbService.getSignTypes({}, function (res) {
      let types = [];
      res.data.forEach(item=>{
        types.push({name:item,checked:false});
      })
      that.data.types=types;
      that.getLocation();
    })
  },

  getLocation(){
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log('获取经纬度成功-->', res);
        app.globalData.header.lat = parseFloat(res.latitude);
        app.globalData.header.lng = parseFloat(res.longitude);
        that.getAddress();
      },
      fail: function (res) {
        console.log('获取经纬度fail', res);
        
        that.getAddress();
      }
    })
  },

  getAddress: function() {
    let that = this
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/',
      method: 'GET',
      data: {
        location: app.globalData.header.lat + ',' + app.globalData.header.lng,
        output: 'json',
        coordtype: 'wgs84ll',
        pois: 1,
        s: 1,
        latest_admin: 1,
        ak: 'GQKwKHdtu8CgmxXIkXdyTkdtlfvML4Gg'
      },
      success(res) {
        console.log('>>', res)
        if (res.data.status == 0&&res.data.result.formatted_address) {
          that.setData({
            address: res.data.result.formatted_address
          })
        }else {
          that.setData({
            address: null,
            top:that.data.onDuty==3?205:360,
            scrollHeight:that.data.onDuty==3?app.getScrollHeight(135):app.getScrollHeight(230),
          })
        }
      },
      fail() {
        that.setData({
          address: null,
          top:that.data.onDuty==3?205:360,
          scrollHeight:that.data.onDuty==3?app.getScrollHeight(135):app.getScrollHeight(230),
        })
      },
      complete(){   
        that.getCitys();
      }
    })
  },

  getCitys: function(){
    let that = this
    lbbService.getCitys({}, function (res) {
      that.setData({
        propArray: res
      })
      that.getHospitalList();
    })
    
  },

  getHospitalList:function(){
    let that = this
    let selectorArray = that.data.selectorArray
    lbbService.getHospitalList({ array: selectorArray,type: 2 }, function (res) {
      that.data.pageNum = 1;
      let resData = res;
      resData.forEach(item=>{
        item.types = JSON.parse(JSON.stringify(that.data.types));
      })
      if(resData&&resData.length > that.data.pageSize){
        that.data.hospitalListSolid = resData;
        that.setHospitalList(resData.slice(0,that.data.pageSize));
      }else {
        that.data.hospitalListSolid = '';
        that.setHospitalList(resData);
      }
    })
  },
  getMoreHos(){
    let that = this;
    let pageSize = that.data.pageSize;
    let hospitalListSolid = that.data.hospitalListSolid;
    let hospitalList = that.data.hospitalList;
    if (hospitalListSolid) {
      hospitalList = hospitalList.concat(hospitalListSolid.slice(that.data.pageNum*pageSize, (that.data.pageNum+1)*pageSize));
      that.data.pageNum++;

      that.setHospitalList(hospitalList);
    }
  },

  //事件处理函数
  myEventListener: function (e) {
    let that = this
    console.log("myEventListener>>", e)
    that.setData({
      selectorArray: e.detail
    })
    that.setMyCar();
    that.getHospitalList()
  },

  /**
   * 输入医院名称搜索
   */
  searchEventListener: function(e){
    let that = this;
    let inputName = '';
    if (e){
      inputName = e.detail;
      that.setData({
        inputName: inputName
      })
    }else {
      inputName = that.data.inputName;
    }
    that.setMyCar();
    if (inputName){
      lbbService.getHospitalByKey({ key: inputName }, function(res){
        that.data.pageNum = 1;
        let resData = res;
        resData.forEach(item=>{
          item.types = JSON.parse(JSON.stringify(that.data.types));
        })
        if(resData&&resData.length > that.data.pageSize){
          that.data.hospitalListSolid = resData;
          that.setHospitalList(resData.slice(0,that.data.pageSize));
        }else {
          that.data.hospitalListSolid = '';
          that.setHospitalList(resData);
        }
      })
    }
  },
  /**
   * 切换医院的出差类型的显示
   */
  toggleShow(e){
    let that = this;
    let index = e.currentTarget.dataset.index;
    let selectedHosList = that.data.selectedHosList;
    selectedHosList[index].show = !selectedHosList[index].show;
    that.setData({
      selectedHosList:selectedHosList,
    })
  },
  /**
   * 删除已经选择的医院
   */
  deleteHos: function(e){
    let that = this;
    let index = e.currentTarget.dataset.index;
    let selectedHosList = that.data.selectedHosList;
    selectedHosList.splice(index,1);
    that.setData({
      selectedHosList: selectedHosList,
    })
    that.setHospitalList();
  },
  /**
   * 设置医院列表，获取医院列表/删除购物车里的医院/点击提交的时候触发，已经在购物车列表的医院，不显示在医院列表里，或disabled
   */
  setHospitalList: function(_hospitalList){
    let that = this;
    let hospitalList = _hospitalList?_hospitalList:that.data.hospitalList;
    let selectedHosList = that.data.selectedHosList;
    if(selectedHosList.length==0){
      that.setData({
        hospitalList: hospitalList
      })
      return;
    }
    hospitalList.forEach(item=>{
      let flg = true;
      selectedHosList.forEach(item1=>{
        if(item.id == item1.id){
          flg = false;
          item.disabled = true;
          item.types = item1.types;
        }
      })
      if(flg){
        item.disabled = false;
      }
    })
    that.setData({
      hospitalList: hospitalList
    })
  },
  /**
   * 设置购物车内容，切换省市区/搜索医院名称/点击提交的时候触发
   */
  setMyCar: function(){
    let that = this;
    let hospitalList = that.data.hospitalList;
    let selectedHosList = that.data.selectedHosList;
    hospitalList.forEach(item=>{
      let flg = true;
      selectedHosList.forEach(item1=>{
        if(item.id==item1.id){
          flg = false;
          item1.types = item.types
        }
      })
      if(flg&&item.checked){
        selectedHosList.push(item);
      }
    })
    that.setData({
      selectedHosList: selectedHosList,
    })
  }
})